﻿using System;
using System.IO;
using System.Linq;
using System.Windows;
using Kotonoha.Server.Core.Db.Updates;
using Kotonoha.Server.Core.Utils;
using Kotonoha.Server.Settings;
using Kotonoha.Server.Utils;
using log4net;
using log4net.Config;

namespace Kotonoha.Server {
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application {
        private readonly ILog log = LogManager.GetLogger(typeof (App));
        private void Application_Startup(object sender, StartupEventArgs e) {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            XmlConfigurator.Configure(new FileInfo(PathUtil.LOG_CONFIG_PATH));
            applyDbScripts();
            bool b = HibernateUtil.Dictionary.Session.Equals(HibernateUtil.Model.Session);
            log.Info("Starting Kotonoha main window");
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
            log.Error("Uncaught Exception", e.ExceptionObject as Exception);
            log.Info("Saving settings");
            SettingsManager.Instance.saveAll();
            log.Info("Shutting down");
            HibernateUtil.shutdown();
        }

        private void applyDbScripts() {
            string[] packages = new[] {"Model", "Dictionary"};
            string[] paths = new[] {PathUtil.DB_PATH, PathUtil.DB_DIC_PATH};
            for (int i = 0; i < packages.Length; i++) {
                var s = packages[i];
                DbUpdater upd = new DbUpdater(s, paths[i]);
                upd.update();
            }
        }

        private void Application_Exit(object sender, ExitEventArgs e) {
            log.Info("Saving settings");
            SettingsManager.Instance.saveAll();
            log.Info("Shutting down");
            HibernateUtil.shutdown();
        }
    }
}
